<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Item详情</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body class="bg-gray-50">
    <!-- 导航栏 -->
    <nav class="bg-white shadow-sm border-b">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between h-16">
                <div class="flex items-center">
                    <a href="/dashboard" class="text-gray-500 hover:text-gray-700 mr-4">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
                        </svg>
                    </a>
                    <h1 id="itemTitle" class="text-xl font-semibold text-gray-900">Item详情</h1>
                </div>
                <div class="flex items-center space-x-4">
                    <button id="editBtn" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg text-sm font-medium">
                        编辑
                    </button>
                    <button id="deleteBtn" class="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-lg text-sm font-medium">
                        删除
                    </button>
                    <button id="logoutBtn" class="text-gray-500 hover:text-gray-700 text-sm">
                        退出登录
                    </button>
                </div>
            </div>
        </div>
    </nav>

    <!-- 主要内容 -->
    <main class="max-w-4xl mx-auto py-6 px-4 sm:px-6 lg:px-8">
        <div class="bg-white rounded-lg shadow-sm border p-6 mb-6">
            <div class="flex justify-between items-start mb-6">
                <div class="flex-1">
                    <h2 id="itemTitleMain" class="text-2xl font-bold text-gray-900 mb-2"></h2>
                    <p id="itemDescription" class="text-gray-600 mb-4"></p>
                </div>
                <div class="text-right">
                    <div class="flex space-x-2 mb-2">
                        <span id="itemTypeBadge" class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium"></span>
                        <span id="itemStatusBadge" class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium"></span>
                        <span id="itemPriorityBadge" class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium"></span>
                    </div>
                    <div class="text-sm text-gray-500">
                        创建于 <span id="itemCreatedAt"></span>
                    </div>
                </div>
            </div>

            <!-- Item信息 -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                <div>
                    <h3 class="text-lg font-medium text-gray-900 mb-3">基本信息</h3>
                    <dl class="space-y-2">
                        <div class="flex">
                            <dt class="text-sm font-medium text-gray-500 w-20">项目:</dt>
                            <dd id="projectName" class="text-sm text-gray-900"></dd>
                        </div>
                        <div class="flex">
                            <dt class="text-sm font-medium text-gray-500 w-20">报告人:</dt>
                            <dd id="reporterName" class="text-sm text-gray-900"></dd>
                        </div>
                        <div class="flex">
                            <dt class="text-sm font-medium text-gray-500 w-20">负责人:</dt>
                            <dd id="assigneeName" class="text-sm text-gray-900"></dd>
                        </div>
                        <div class="flex">
                            <dt class="text-sm font-medium text-gray-500 w-20">更新时间:</dt>
                            <dd id="itemUpdatedAt" class="text-sm text-gray-900"></dd>
                        </div>
                    </dl>
                </div>
                <div>
                    <h3 class="text-lg font-medium text-gray-900 mb-3">状态管理</h3>
                    <div class="space-y-3">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">状态</label>
                            <select id="statusSelect" class="w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                                <option value="pending">待处理</option>
                                <option value="in_progress">进行中</option>
                                <option value="completed">已完成</option>
                                <option value="closed">已关闭</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">优先级</label>
                            <select id="prioritySelect" class="w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                                <option value="low">低</option>
                                <option value="medium">中</option>
                                <option value="high">高</option>
                                <option value="urgent">紧急</option>
                            </select>
                        </div>
                        <button id="updateStatusBtn" class="w-full bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-md text-sm font-medium">
                            更新状态
                        </button>
                    </div>
                </div>
            </div>

            <!-- 图片区域 -->
            <div class="mb-6">
                <h3 class="text-lg font-medium text-gray-900 mb-3">相关图片</h3>
                <div id="imagesContainer" class="grid grid-cols-2 md:grid-cols-4 gap-4">
                    <!-- 图片将通过JavaScript动态加载 -->
                </div>
                <div id="noImagesMsg" class="text-center py-8 text-gray-500 hidden">
                    暂无图片
                </div>
            </div>
        </div>
    </main>


    <script>
        let currentItem = null;

        $(document).ready(function() {
            const itemId = window.location.pathname.split('/').pop();
            loadItem(itemId);
            
            // 编辑按钮事件 - 跳转到编辑页面
            $('#editBtn').click(function() {
                const itemId = window.location.pathname.split('/').pop();
                window.location.href = `/items/${itemId}/edit`;
            });
            
            
            // 更新状态
            $('#updateStatusBtn').click(function() {
                const status = $('#statusSelect').val();
                const priority = $('#prioritySelect').val();
                
                $.ajax({
                    url: `/api/items/${itemId}`,
                    method: 'PUT',
                    contentType: 'application/json',
                    data: JSON.stringify({
                        status: status,
                        priority: priority
                    }),
                    success: function(response) {
                        loadItem(itemId);
                        showNotification('状态更新成功！', 'success');
                    },
                    error: function(xhr) {
                        const error = xhr.responseJSON?.error || '更新状态失败';
                        showNotification(error, 'error');
                    }
                });
            });
            
            // 删除按钮事件
            $('#deleteBtn').click(function() {
                if (confirm('确定要删除这个Item吗？此操作不可撤销。')) {
                    $.ajax({
                        url: `/api/items/${itemId}`,
                        method: 'DELETE',
                        success: function(response) {
                            showNotification('Item删除成功！', 'success');
                            setTimeout(function() {
                                window.location.href = '/dashboard';
                            }, 1500);
                        },
                        error: function(xhr) {
                            const error = xhr.responseJSON?.error || '删除Item失败';
                            showNotification(error, 'error');
                        }
                    });
                }
            });
            
            // 退出登录
            $('#logoutBtn').click(function() {
                $.ajax({
                    url: '/api/logout',
                    method: 'POST',
                    success: function() {
                        window.location.href = '/login';
                    }
                });
            });
        });
        
        function loadItem(itemId) {
            $.ajax({
                url: `/api/items/${itemId}`,
                method: 'GET',
                success: function(response) {
                    currentItem = response.item;
                    displayItem(currentItem);
                },
                error: function(xhr) {
                    console.error('Failed to load item:', xhr);
                    showNotification('加载Item失败', 'error');
                }
            });
        }
        
        function displayItem(item) {
            // 更新标题
            $('#itemTitle').text(item.title);
            $('#itemTitleMain').text(item.title);
            $('#itemDescription').text(item.description || '暂无描述');
            
            // 更新状态和优先级选择器
            $('#statusSelect').val(item.status);
            $('#prioritySelect').val(item.priority);
            
            // 更新徽章
            updateBadges(item);
            
            // 更新基本信息
            $('#projectName').text(item.project ? item.project.name : '未知项目');
            $('#reporterName').text(item.reporter ? item.reporter.name : '未知用户');
            $('#assigneeName').text(item.assignee ? item.assignee.name : '未分配');
            $('#itemCreatedAt').text(new Date(item.created_at).toLocaleString());
            $('#itemUpdatedAt').text(new Date(item.updated_at).toLocaleString());
            
            // 更新图片
            displayImages(item.pictures || []);
        }
        
        function updateBadges(item) {
            const typeColors = {
                'task': 'bg-green-100 text-green-800',
                'issue': 'bg-red-100 text-red-800',
                'requirement': 'bg-blue-100 text-blue-800'
            };
            
            const statusColors = {
                'pending': 'bg-yellow-100 text-yellow-800',
                'in_progress': 'bg-blue-100 text-blue-800',
                'completed': 'bg-green-100 text-green-800',
                'closed': 'bg-gray-100 text-gray-800'
            };
            
            const priorityColors = {
                'low': 'bg-gray-100 text-gray-800',
                'medium': 'bg-blue-100 text-blue-800',
                'high': 'bg-orange-100 text-orange-800',
                'urgent': 'bg-red-100 text-red-800'
            };
            
            const typeNames = {
                'task': '任务',
                'issue': '问题',
                'requirement': '需求'
            };
            
            const statusNames = {
                'pending': '待处理',
                'in_progress': '进行中',
                'completed': '已完成',
                'closed': '已关闭'
            };
            
            const priorityNames = {
                'low': '低',
                'medium': '中',
                'high': '高',
                'urgent': '紧急'
            };
            
            $('#itemTypeBadge').removeClass().addClass('inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ' + typeColors[item.type]).text(typeNames[item.type]);
            $('#itemStatusBadge').removeClass().addClass('inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ' + statusColors[item.status]).text(statusNames[item.status]);
            $('#itemPriorityBadge').removeClass().addClass('inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ' + priorityColors[item.priority]).text(priorityNames[item.priority]);
        }
        
        function displayImages(pictures) {
            const container = $('#imagesContainer');
            const noImagesMsg = $('#noImagesMsg');
            
            if (pictures.length === 0) {
                container.addClass('hidden');
                noImagesMsg.removeClass('hidden');
                return;
            }
            
            container.removeClass('hidden');
            noImagesMsg.addClass('hidden');
            container.empty();
            
            pictures.forEach(function(picture) {
                const imageElement = $(`
                    <div class="relative group">
                        <img src="/api/images/${picture.filename}" alt="${picture.original_name}" 
                             class="w-full h-32 object-cover rounded-lg border">
                        <div class="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-30 transition-all duration-200 rounded-lg flex items-center justify-center">
                            <button class="opacity-0 group-hover:opacity-100 bg-red-600 hover:bg-red-700 text-white px-2 py-1 rounded text-xs delete-image-btn" 
                                    data-picture-id="${picture.id}">
                                删除
                            </button>
                        </div>
                    </div>
                `);
                container.append(imageElement);
            });
        }
        
        function showNotification(message, type) {
            const bgColor = type === 'success' ? 'bg-green-500' : 'bg-red-500';
            const notification = $(`
                <div class="fixed top-4 right-4 ${bgColor} text-white px-6 py-3 rounded-lg shadow-lg z-50">
                    ${message}
                </div>
            `);
            
            $('body').append(notification);
            
            setTimeout(function() {
                notification.fadeOut(function() {
                    notification.remove();
                });
            }, 3000);
        }
    </script>
</body>
</html>
